<template>
    <div>

      <v-form v-model="valid" ref="heimaleyou">
        <v-text-field label="请输入品牌名称" v-model="brand.name" required :rules="nameRules"/>
        <v-text-field label="请输入品牌首字母" v-model="brand.letter" required :rules="letterRules"/>

      </v-form>

      <v-cascader
        url="/item/category/list"
        multiple
        required
        v-model="brand.categories"
        label="请选择商品分类"/>



      <v-layout row>
        <v-flex xs3>
          <span style="font-size: 16px; color: #444">品牌LOGO：</span>
        </v-flex>
        <v-flex>
          <v-upload
            v-model="brand.image"
            url="/upload/image"
            :multiple="false"
            :pic-width="250"
            :pic-height="90"
          />
        </v-flex>
      </v-layout>

      <v-layout class="my-4" row>
        <v-spacer/>
        <v-btn @click="submit" color="primary">提交</v-btn>
        <v-btn @click="clear" >重置</v-btn>
      </v-layout>

    </div>

</template>

<script>
  export default {
    name: "MyBrandForm",
    props:{
      oldBrand:{
        type:Object,
        default:{}

      },
      edit:{
        type:Boolean,
        default:false

      }
    },
    data() {
      return {
        valid: false,
        nameRules:[
          v => !!v || "品牌不能为空",
          v => v.length>1 || "品牌名称至少2位"

        ],
        letterRules:[
          v => !!v || "首字母不能为空",
          v => /^[A-Z,a-z]{1}$/.test(v) || "品牌字母只能是字母"

        ],
        brand: {
          name: "",
          letter: "",
          categories:[],
          image:""


        }

      }
    },
    methods:{
      submit() {
        if (this.valid) {
          //解构brand对象用来删除categories属性,形成新的对象others
          let {categories,letter,...others} = this.brand;

          //把categories对象中id取出,并整合成字符串.名称为cids
          let cids = categories.map(categories => categories.id).join();
          //将字母转换成大写

          others.letter = letter.toUpperCase();

          //给others对象添加一个属性名为cids,值为分类的对个id组成的字符串
          others.cids = cids;


          this.$http({
            method:this.edit?"put":"post",
            url:"/item/brand",
            data:this.$qs.stringify(others)

          })
            .then(resp=>{
              this.$emit("close")
                this.$message.success((this.edit?"修改":"新增")+"品牌成功")


            }).catch(resp=>{
            this.$message.error((this.edit?"修改":"新增")+"品牌失败")
          })
        }

      },
      clear() {

        this.$refs.heimaleyou.reset();
        this.brand.categories = [];

      }

    },
    watch:{
      oldBrand:{
        deep:true,
        handler(val){
          if (val) {
            this.brand = Object.deepCopy(val);
          }else {
            //为空,初始化brand
            this.brand = {
              name: "",
              letter:"",
              image:"",
              categories:[]
            };
            }
          }
        }
      }
  };
</script>

<style scoped>

</style>
